//
//  NSObject+RuntimeArchiver.m
//  RuntimeArchiver
//
//  Created by QC.L on 16/4/6.
//  Copyright © 2016年 QC.L. All rights reserved.
//

#import "NSObject+RuntimeArchiver.h"
#import <objc/objc-runtime.h>

@implementation NSObject (RuntimeArchiver)

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [self init];
    if (self) {
        NSArray *properNames = [[self class] propertyList];
        for (NSString *propertyName in properNames) {
            [self setValue:[aDecoder decodeObjectForKey:propertyName] forKey:propertyName];
        }
    }
    return self;
}

+ (NSArray *)propertyList {
    
    NSMutableArray *array = [NSMutableArray array];
    unsigned int propertyListCount = 0;
    objc_property_t *propertyList = class_copyPropertyList([self class], &propertyListCount);
    for (int i = 0; i < propertyListCount; i++) {
        NSString *property = [NSString stringWithUTF8String:property_getName(propertyList[i])];
        [array addObject:property];
    }

    return [array copy];
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    NSArray *propertyList = [[self class] propertyList];
    for (NSString *propertyName in propertyList) {
        [aCoder encodeObject:[self valueForKey:propertyName] forKey:propertyName];
    }
}
@end
